package com.tencent.compose.map.poi.data

import org.example.project.search.LaserUtil
import org.example.project.search.data.MergeSCSugRsp
import org.example.project.search.data.SCSuggestionRsp
import org.example.project.search.data.SgSubPois
import org.example.project.search.data.SignInfo
import org.example.project.search.data.SugData
import org.example.project.search.data.SugHeader
import org.example.project.search.data.Suggestion
import org.example.project.search.data.SuggestionData
import org.example.project.search.data.SuggestionHintData
import org.example.project.search.data.TipsInfo
import kotlin.jvm.JvmStatic

class ConvertData {
    companion object {
        const val TAG: String = "ConvertData"

        /**
         * 获取营业时间高亮键值云控
         */
        const val OPERATING_STATE_KEYWORDS: String = "operatingStateKeywords"

        /**
         * 0字符串
         */
        const val ZERO_STRING: String = "0"

        /**
         * 不展示距离
         */
        const val NO_SHOW_DISTANCE: String = "-1"

        /**
         * 距离定位点在此范围内的站，有资格竞选“离我最近”的站
         */
        const val NEARBY_DISTANCE: Int = 1000


        /**
         * sug接口返回类型转换成客户端使用的Suggestion
         */
        @JvmStatic
        fun convertSugData(response: SCSuggestionRsp): SugData {
            var requestId = "";
            if (response.tInfo !== null) {
                requestId = response.tInfo.request_id ?: ""
            }
            var isAddLocTips = false
            if (response.tInfo !== null && response.tInfo.add_info !== null) {
                val addLocTips = response.tInfo.add_info["add_loc_tips"] ?: ""
                isAddLocTips = addLocTips == "1"
            }

            val sugData: SugData
            if (response.vSuggestionList?.size == 0 && response.mergeSugData?.size == 0) {
                sugData = SugData()
                sugData.isAddLocTips = isAddLocTips
                return sugData
            }
            sugData = processMergeSugData(response, requestId)
            sugData.isAddLocTips = isAddLocTips
            // 如果response的vSuggestionList不为空，调用方法转换并合并数据到suggestionList

            if (!response.vSuggestionList.isNullOrEmpty()) {
                val convertedSuggestions =
                    convertSuggestionListWithHint(response, requestId, null)
                sugData.suggestionList.addAll(convertedSuggestions)
            }
            // 根据response的tInfo情况设置total属性值
            sugData.total = response.tInfo?.total ?: 0
            addFooter(sugData.suggestionList, response)
            return sugData
        }

        @JvmStatic
        private fun processMergeSugData(response: SCSuggestionRsp, requestId: String): SugData {
            val mergeSugData: List<MergeSCSugRsp> = response.mergeSugData ?: mutableListOf()
            val sugData = SugData()
            if (mergeSugData.isEmpty()) {
                obtainSugConfusionInfo(response, sugData);
                return sugData;
            }

            val result: MutableList<Suggestion> = mutableListOf()
            val sugCityTabs: MutableMap<String, Int> = mutableMapOf()
            var cityIndex = 1
            var isCityTabExist = false
            var highlightFreq: Number = Suggestion.HIGHLIGHT_FIRST;
            if (response.tInfo !== null) {
                isCityTabExist = response.tInfo.citybar_exist == Suggestion.CITY_BAR_EXIST;
                highlightFreq = response.tInfo.highlight_freq ?: Suggestion.HIGHLIGHT_FIRST;
            }


            for (rsp in mergeSugData) {
                val suggestion = Suggestion()
                suggestion.type = Suggestion.TYPE_MERGED_CITY.toLong();
                suggestion.folderNumer = rsp.flod_num ?: 0
                suggestion.cityName = rsp.cityNamme
                suggestion.requestId = requestId
                suggestion.cityIndex = cityIndex

                suggestion.suggestionsInCity = convertSuggestionList(
                    rsp.vSuggestionList ?: listOf(),
                    requestId,
                    rsp.cityNamme ?: "",
                    highlightFreq
                )
                suggestion.shortCityName = rsp.short_cityname;

                if (isCityTabExist) {
                    assignCityTabs(sugCityTabs, cityIndex, suggestion);
                }

                result += suggestion
                suggestion.showPoiCount = suggestion.suggestionsInCity?.size ?: 0
                cityIndex++;
            }

            if (sugCityTabs.isNotEmpty()) {
                val sugHeader = SugHeader()
                sugHeader.sugCityTabs = sugCityTabs;
                sugData.sugHeader = sugHeader;
            }

            sugData.suggestionList = result;
            return sugData
        }

        @JvmStatic
        fun addFooter(results: MutableList<Suggestion>, sugList: SCSuggestionRsp) {
            if (sugList.tInfo == null) {
                return;
            }
            if (sugList.tInfo.tail_exist != 1) {
                return;
            }
            if (sugList.tInfo.tail_text === "") {
                return;
            }
            if (sugList.tInfo.tail_url === "") {
                return;
            }
            val footer = Suggestion();
            footer.type = Suggestion.TYPE_FOOTER.toLong()
            footer.footerText = sugList.tInfo.tail_text;
            footer.footerJumpUrl = sugList.tInfo.tail_url;
            results += footer
        }

        /**
         * sug接口返回类型转换成客户端使用的Suggestion
         */
        @JvmStatic
        fun convertSuggestionListWithHint(
            response: SCSuggestionRsp, requestId: String,
            cityName: String?
        ): List<Suggestion> {
            var hintList: List<SuggestionHintData>? = response.vSuggestionHintList
            var hintSize = 0;
            var hintMap: MutableMap<Int, Suggestion> = mutableMapOf();
            if (!hintList.isNullOrEmpty()) {
                hintSize = hintList.size
            }
            // 将插入文案存为map
            convertHintDataToSuggestion(hintMap, hintList!!);
            var highlightFreq = Suggestion.HIGHLIGHT_FIRST;
            if (response.tInfo != null) {
                highlightFreq = response.tInfo.highlight_freq ?: Suggestion.HIGHLIGHT_FIRST;
            }
            val sugList: List<SuggestionData>? = response.vSuggestionList
            val result: MutableList<Suggestion> = mutableListOf()
            sugList?.forEachIndexed { index, item ->
                if (hintMap[index + 1] != null) {
                    result.add(hintMap[index + 1]!!)
                }
                val data = sugList[index]
                val suggestion = getSuggestion(requestId, cityName, highlightFreq, data)
                result.add(suggestion)
            }
            return result;
        }

        @JvmStatic
        fun convertHintDataToSuggestion(
            hintMap: MutableMap<Int, Suggestion>,
            hintList: List<SuggestionHintData>
        ) {
            if (hintList.isEmpty()) {
                return
            }

            hintList.forEach { suggestionHintData ->
                if (suggestionHintData != null) {
                    val suggestion = Suggestion()
                    suggestion.type = Suggestion.TYPE_HINT.toLong()
                    suggestion.hintData = suggestionHintData;
                    hintMap[suggestionHintData.hint_index!!] = suggestion
                }
            }
        }

        @JvmStatic
        fun assignCityTabs(
            sugCityTabs: MutableMap<String, Int>,
            cityIndex: Int,
            suggestion: Suggestion
        ) {
            // 有短名时使用短名
            if (suggestion.shortCityName === "") {
                suggestion.shortCityName = suggestion.cityName;
            }
            if (!suggestion.shortCityName.isNullOrBlank() && suggestion.shortCityName?.uppercase() === Suggestion.OTHER_CITIES) {
                suggestion.shortCityName = Suggestion.OTHER_CITY_STR;
            }
            if (!suggestion.shortCityName.isNullOrBlank()) {
                sugCityTabs[suggestion.shortCityName!!] = cityIndex - 1
            }
        }

        /**
         * 获取后台返回的sug混淆信息
         *
         * @param response
         * @param sugData
         */
        @JvmStatic
        private fun obtainSugConfusionInfo(response: SCSuggestionRsp, sugData: SugData) {
            if (response.tInfo?.add_info == null) {
                return
            }
            val confused = response.tInfo.add_info["confused"]
            if (confused.isNullOrBlank()) {
                return
            }
            val results = confused.split("-")
            if (results.isEmpty() || results.size != 2) {
                return
            }
            val firstValue = results[0].toInt()
            val secondValue = results[1].toInt()
            if (firstValue <= 0 || secondValue <= 0) {
                return
            }
            sugData.showSugConfusionTips = true;
            if (firstValue < secondValue) {
                sugData.sugItemConfusionStartIndex = firstValue;
                sugData.sugItemConfusionEndIndex = secondValue;
            } else {
                sugData.sugItemConfusionStartIndex = secondValue;
                sugData.sugItemConfusionEndIndex = firstValue;
            }
        }

        @JvmStatic
        fun convertSuggestionList(
            sugList: List<SuggestionData>,
            requestId: String,
            cityName: String,
            highlightFreq: Number
        ): List<Suggestion> {
            if (sugList.isEmpty()) {
                return listOf()
            }
            val result: MutableList<Suggestion> = mutableListOf()
            for (data in sugList) {
                val suggestion: Suggestion =
                    getSuggestion(requestId, cityName, highlightFreq, data);
                result += suggestion
            }
            return result;
        }

        @JvmStatic
        fun getSuggestion(
            requestId: String,
            cityName: String?,
            highlightFreq: Number,
            data: SuggestionData
        ): Suggestion {
            val suggestion = Suggestion()
            // 数据请求id，统计使用
            suggestion.requestId = requestId;
            // 数据id
            suggestion.id = data.strUid;
            // 名称
            suggestion.name = data.strName;
            suggestion.showName = data.strName;
            suggestion.city = getCity(data);
            // 经纬度
            if (data.stPos != null) {
                // 这里假设已经有对应的在ArkTS里获取经纬度的函数，需准确实现其逻辑
                suggestion.latLng =
                    LaserUtil.getLatLng(
                        data.stPos.latitude ?: 0.0,
                        data.stPos.longitude ?: 0.0
                    );
            }
            // sug类型
            suggestion.type = data.uiType ?: 0
            // 美食或者酒店类型
            suggestion.coType = data.co_type ?: 0
            // 类别词
            suggestion.typeWord = data.strClass;
            // 距离
            suggestion.distance = data.dist;
            // 地址
            suggestion.address = data.strAddr;
            // 途经线路
            suggestion.sgPassLines = data.lines;
            // 评分，100分满分
            suggestion.starLevel = data.star_level ?: 0
            // 到访人数
            suggestion.arrival = data.strAccess;
            // 实时公交
            // suggestion.realtime = data.realtime;
            // 城市码
            suggestion.nSO = data.uiAdcode ?: 0
            suggestion.nCO = data.uiTypeCode ?: 0
            // 室内信息
            suggestion.building_id = data.building_id;
            if (suggestion.building_id === "") {
                suggestion.building_id = "";
            }
            suggestion.shinei_id = data.shinei_id;
            suggestion.floor_id = data.floor_id;
            suggestion.floor_name = data.floor_name;

            // POI信息
            suggestion.poiErrInfo = data.strPOIErrInfo;
            // POI信息颜色
            suggestion.nplColor = data.strNPLColor;

            suggestion.cityName = cityName;
            suggestion.reviewTag = data.reviewTag;
            // 子点sug
            suggestion.subSuggestions = convertSubSuggestionList(requestId, data)
            suggestion.districtType = data.districtType ?: 0
            // 直达信息
            suggestion.searchdirect = data.searchdirect;
            // 设置端地址
            suggestion.shortAddress = data.shortAddr;
            // 设置头图url
            suggestion.picUrl = data.pic_url ?: ""
            // 召回标签
            suggestion.recallTag = data.recallTag;
            // 去这里标记
            suggestion.showDis = data.showDis;
            // 均价
            suggestion.priceInfo = data.priceInfo;
            // 小程序图标
            suggestion.icons = data.icons
            // 小程序信息
            suggestion.miniApp = data.miniapp;

            // 标签类型
            suggestion.labelType = data.label_type;

            // tip的信息
            suggestion.themeTipInfo = data.themeTipInfo;

            // 标签颜色
            if (!data.label_color.isNullOrBlank()) {
                val colors = data.label_color.split(";");
                if (colors.size == 2) {
                    suggestion.labelStrokeColor = colors[1];
                    suggestion.labelTextColor = colors[0];
                }
            }

            // 猜你想搜和主子词 - 带icon
            suggestion.guessInfo = data.sug_guess;

            suggestion.aliasTypeStr = data.alias_type;
            suggestion.aliasName = data.alias;
            if (!data.highlight_list.isNullOrEmpty()) {
                suggestion.highlightPositions = HashMap<Int, String>()
                data.highlight_list.forEachIndexed { index, i ->
                    suggestion.highlightPositions?.put(index, i.toString())
                }
            }
            suggestion.highLightFreq = highlightFreq.toInt()
            suggestion.highlightText = data.highlight_text;
            suggestion.additionalInfo = data.additional_info;
            // 实时人气
            if (data.additional_info.isNotEmpty()) {
                suggestion.behavior = data.additional_info["behavior_msg"];
                suggestion.peopleFlow = data.additional_info["people_flow"];
            }
            if (data.poi_info != null) {
                if (data.poi_info.title != null) {
                    val info1 = TipsInfo(
                        content = data.poi_info.title?.content,
                        color = data.poi_info.title?.color,
                        status = data.poi_info.title?.status
                    )
                    suggestion.title = info1;
                }
                if (data.poi_info.detail != null) {
                    val info2 = TipsInfo(
                        content = data.poi_info.title?.content,
                        color = data.poi_info.title?.color,
                        status = data.poi_info.title?.status
                    )
                    suggestion.detail = info2
                }
                if (data.poi_info.look != null) {
                    val info3 = TipsInfo(
                        content = data.poi_info.title?.content,
                        color = data.poi_info.title?.color,
                        status = data.poi_info.title?.status
                    )
                    suggestion.look = info3;
                }
                if (data.poi_info.sign != null) {
                    val info4 = SignInfo(
                        pic = data.poi_info.sign?.pic,
                        status = data.poi_info.sign?.status,
                        error_code = data.poi_info.sign?.error_code,
                    )
                    suggestion.sign = info4;
                }
                if (data.poi_info.poi_info_url.isNullOrBlank()) {
                    suggestion.poiInfoUrl = data.poi_info.poi_info_url;
                }
                if (data.poi_info.poi_info_type.isNullOrBlank()) {
                    suggestion.poiInfoType = data.poi_info.poi_info_type;
                }
                if (data.poi_info.poi_info_tag.isNullOrBlank()) {
                    suggestion.poiInfoTag = data.poi_info.poi_info_tag;
                }
            }
            return suggestion;
        }

        @JvmStatic
        fun getCity(sugData: SuggestionData): String {
            if (sugData.stCity != null && sugData.stCity.code_name != null) {
                return sugData.stCity.code_name.cname ?: ""
            }
            return "";
        }

        @JvmStatic
        fun convertSubSuggestionList(requestId: String, data: SuggestionData): List<Suggestion> {
            val subSuggestions: MutableList<Suggestion> = mutableListOf()
            // sug子点
            if (!data.subpois.isNullOrEmpty()) {
                data.subpois.forEachIndexed { index, item ->
                    val subPoi: SgSubPois = item
                    val subSuggestion = Suggestion()
                    subSuggestion.requestId = requestId;
                    subSuggestion.id = subPoi.uid;
                    subSuggestion.name = subPoi.name;
                    subSuggestion.showName = subPoi.show;
                    if (subPoi.point != null) {
                        subSuggestion.latLng =
                            LaserUtil.getLatLng(
                                subPoi.point?.latitude ?: 0.0,
                                subPoi.point?.longitude ?: 0.0
                            );
                    }
                    subSuggestion.type = subPoi.type ?: 0
                    // 美食或者酒店类型
                    subSuggestion.coType = data.co_type ?: 0
                    subSuggestion.typeWord = subPoi.strClass;
                    subSuggestion.distance = subPoi.dist;
                    subSuggestion.address = subPoi.addr;
                    subSuggestion.sgPassLines = subPoi.lines
                    subSuggestion.starLevel = subPoi.star_level ?: 0
                    subSuggestion.arrival = subPoi.strAccess;
                    if (subPoi.slave != null) {
                        subSuggestion.subSugProb = subPoi.slave?.slave_prob ?: 0f
                        subSuggestion.subSugProbColor = subPoi.slave?.slave_color;
                    }
                    // sug子点中的POI标签
                    if (!subPoi.reviewTag.isNullOrEmpty()) {
                        subSuggestion.reviewTag = subPoi.reviewTag
                    }
                    subSuggestions += subSuggestion
                }
            }
            // 继续添加子点
            if (!data.sub.isNullOrEmpty()) {
                data.sub.forEachIndexed { index, it ->
                    val subData = it
                    val subSuggestion = Suggestion()
                    subSuggestion.requestId = requestId;
                    subSuggestion.id = subData.strUid;
                    subSuggestion.name = subData.strName;
                    subSuggestion.showName = subData.strName;
                    subSuggestion.type = subData.uiType ?: 0
                    // 美食或者酒店类型
                    subSuggestion.coType = data.co_type ?: 0
                    subSuggestion.typeWord = subData.strClass;
                    subSuggestion.address = subData.strAddr;
                    subSuggestion.sgPassLines = subData.lines
                    subSuggestion.starLevel = subData.star_level ?: 0
                    subSuggestion.arrival = subData.strAccess;
                    subSuggestions += subSuggestion
                }
            }
            // 猜你想搜\ 主子词带 icon 子点
            if (data.sug_guess != null && !data.sug_guess.sublist.isNullOrEmpty()) {
                data.sug_guess.sublist!!.forEachIndexed { index, item ->
                    val subSuggestion = Suggestion()
                    subSuggestion.requestId = requestId;
                    subSuggestion.name = item.name;
                    subSuggestion.type = data.uiType ?: 0
                    subSuggestion.coType = data.co_type ?: 0
                    subSuggestions += subSuggestion
                }
            }

            return subSuggestions;
        }

    }


}